//
//  DBTool.m
//  FTDL
//
//  Created by QSC on 2018/7/31.
//  Copyright © 2018年 macbook. All rights reserved.
//

#import "DBTool.h"
#import <FMDB/FMDB.h>
@implementation DBTool


static FMDatabaseQueue *_queue;
+(void)initialize{
    // 0.获得沙盒中的数据库文件名
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"data.sqlite"]];
    

    // 1.创建队列
    _queue = [FMDatabaseQueue databaseQueueWithPath:path];
    
    // 2.创表
    
    [_queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"create table if not exists t_DB(id integer primary key autoincrement, tag char,  dic blob,UNIQUE (tag));"];
    }];
}


//保存数据
+ (void)saveData:(NSDictionary *)dic tag:(NSString*)tag;
{
    [_queue inDatabase:^(FMDatabase *db) {
        // 1.获得需要存储的数据
        
        
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];
        //如果之前有，先删除原来的缓存
        NSString *del= [NSString stringWithFormat:@"DELETE FROM t_DB WHERE tag='%@'",tag];
        [db executeUpdate:del];
        
        // 2.存储数据
        [db executeUpdate:@"insert into t_DB(tag,dic) values(?, ? )", tag, data];
    }];
}
+ (NSDictionary *)getData:(NSString*)tag;
{
    // 1.定义数组
    __block NSMutableArray *modelArray = nil;
    
    // 2.使用数据库
    [_queue inDatabase:^(FMDatabase *db) {
        // 创建数组
        modelArray = [NSMutableArray array];
        
        FMResultSet *rs = nil;
        NSString *select= [NSString stringWithFormat:@"select * from t_DB WHERE tag='%@'",tag];
        rs = [db executeQuery:select ];
        
        while (rs.next) {
            NSData *data = [rs dataForColumn:@"dic"];
            NSDictionary *dict= [NSKeyedUnarchiver unarchiveObjectWithData:data];
            
            [modelArray addObject:dict];
        }
    }];
    

    if(modelArray.count)
    {
        // 3.返回数据
        return modelArray[0];
    }
    
    
    
    return [NSDictionary dictionary];
}

@end
